package com.spice.im.group;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import com.beem.push.utils.AsyncTask;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.R;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.ImageFetcher;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.stb.core.chat.ContactGroup;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.service.aidl.IRoster;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.BeemConnectivity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class GroupNew2Activity extends Activity implements OnItemClickListener,OnClickListener {
	
	private Context mContext;
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));
	}
	private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    protected FlippingLoadingDialog mLoadingDialog;
    private HeaderLayout mHeaderLayout;
	
    private static final String TAG = "GroupDetailsActivity";
    private final ServiceConnection mServConn = new BeemServiceConnection();
    
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}		    
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
//	private ImageFetcher mImageFetcher;
	
	private List<ContactGroup> friends_cGroup;//ContactFrameActivity.java 中传递过来
	private ContactGroup cGroup;
	int cgrouptype = 0;
	private String CurrentUserAvatorPath = "";
    private String groupId;
    private String groupName;
    private List<String> exitingMembers = new ArrayList<String>();
    private static final int MESSAGE_UPDATE_SEND_BTN = 0x00020001;
	private static final int MESSAGE_BIND_FRIEND_LIST = 0x00020002;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case MESSAGE_UPDATE_SEND_BTN:
//					int count = (int) msg.obj;
					String count = (String) msg.obj;
		//			sureBtn.setText("确定(" + count + ")");
					break;
				case MESSAGE_BIND_FRIEND_LIST:
					bindAdapter();
					
					break;
			}
		}
	};
	
	public void bindAdapter(){
		adapter.setData(friends_cGroup);
		lvContact.setAdapter(adapter);
		lvContact.setOnItemClickListener(this);
		
		checkedAdapter.setDefaultimg(CurrentAvatarpath);
		
	}
    
	private ListView lvContact;
	private HorizontalListView checkedContack;
	private ContactAdapter adapter;
	private CheckedImgAdapter checkedAdapter;
	private Button makesureBtn;
	private ArrayList<CheckedImg> checkedList;

	public static class CheckedImg {
		public String touxiang;
		public String name;
		public String id;
	}

	private void initCheckedList() {
		CheckedImg img = new CheckedImg();
		img.id = "default";
		img.name = "default";
//		img.touxiang = "none";
		img.touxiang = CurrentAvatarpath;
		checkedList.add(img);
	}

	/**
	 * 移除水平图片.
	 * 
	 * @param _name
	 */
	private void removeByName(String _name) {
		checkedList.remove(findCheckedPositionByName(_name));
		if (checkedList.size() == 4) {
			if (findCheckedPositionByName("default") == -1) {
				CheckedImg img = new CheckedImg();
				img.id = "default";
				img.name = "default";
//				img.touxiang = "none";
				img.touxiang = CurrentAvatarpath;
				checkedList.add(img);
			}
		}
		makesureBtn.setText("确定(" + --countChecked + ")");
	}

	/**
	 * 选择checkbox，添加水平图片.
	 * 
	 * @param _name
	 * @param _id
	 * @param _touxiang
	 */
	private void addToCheckedList(String _name, String _id, String _touxiang) {
		CheckedImg map2 = new CheckedImg();
		map2.name = _name;
		map2.id = _id;
		map2.touxiang = _touxiang;
		if (checkedList.size() < maxCount)
			checkedList.add(checkedList.size() - 1, map2);
		else
			checkedList.add(map2);

		if (checkedList.size() == maxCount + 1) {
			if (findCheckedPositionByName("default") != -1)
				checkedList.remove(findCheckedPositionByName("default"));
		} else if (checkedList.size() == maxCount - 1) {
			if (findCheckedPositionByName("default") == -1) {
				CheckedImg img = new CheckedImg();
				img.id = "default";
				img.name = "default";
//				img.touxiang = "none";
				img.touxiang = CurrentAvatarpath;
				checkedList.add(img);
			}
		}
		makesureBtn.setText("确定(" + ++countChecked + ")");
	}

	private boolean hasMeasured = false;
	private int maxCount = 5;// 这里要是可以根据屏幕计算出来最多容纳多少item就好了.没有找到合适的方法.
	private int countChecked = 0;// 得到选中的数量.

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_group_new2);
		mContext = this;
		mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
////		mHeaderLayout.init(HeaderStyle.DEFAULT_TITLE);
//		mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
//		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
//				R.drawable.bg_chat_dis_active, "发起群聊",
//				"",
//				R.drawable.ic_menu_invite,//ic_menu_invite  ic_topbar_profile
//				new OnMiddleImageButtonClickListener(),
//				R.drawable.return2,
//				new OnRightImageButtonClickListener());
		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.setTitleRightImageButton("发起群聊", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
        // 获取传过来的groupid
        groupId = getIntent().getStringExtra("groupId");
        groupName = getIntent().getStringExtra("groupName");
        
        CurrentUid = getIntent().getStringExtra("CurrentUid");
        CurrentName = getIntent().getStringExtra("CurrentName");
        CurrentAvatarpath = getIntent().getStringExtra("CurrentAvatarpath");
        
//        mImageFetcher = new ImageFetcher(this, 240);
//        mImageFetcher.setUListype(0);////0普通图片listview 1瀑布流  2地图模式
//        mImageFetcher.setLoadingImage(R.drawable.empty_photo4);
        
		lvContact = (ListView) this.findViewById(R.id.ListView_catalog);
		adapter = new ContactAdapter(GroupNew2Activity.this);//初始化好友列表数据
//		lvContact.setAdapter(adapter);
//		lvContact.setOnItemClickListener(this);

		checkedContack = (HorizontalListView) this.findViewById(R.id.imgList);
		checkedList = new ArrayList<CheckedImg>();
		initCheckedList();
		checkedAdapter = new CheckedImgAdapter(GroupNew2Activity.this, checkedList);
		makesureBtn = (Button) findViewById(R.id.makesureBtn);
		makesureBtn.setOnClickListener(this);//
		checkedContack.setAdapter(checkedAdapter); 
		checkedContack.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				CheckedImg img = checkedList.get(position);
				Map<Integer, Boolean> checkedMap = adapter.getCheckedMap();
				if (!img.id.equals("default")) {
					checkedMap.put(Integer.parseInt(img.id), false);
					adapter.notifyDataSetChanged();
					removeByName(img.name);
				}
				checkedAdapter.notifyDataSetChanged();
			}
			
		});
		
	}
    public void delItem_friends_cGroup(List<String> exitingMembers) {
    	int idx = -1;
    	if(exitingMembers!=null){
        	for (String uid : exitingMembers) {
        		idx = containsKey(uid);
        		if(idx!=-1)
        			friends_cGroup.remove(idx);
            }
    	}
    }
    public int containsKey(String key){
    	int i = 0;
    		Iterator<ContactGroup> it = friends_cGroup.iterator();
    		ContactGroup di;
    		String tmp_uid;
    		while(it.hasNext()){
    			di = it.next();
    			tmp_uid = StringUtils.parseBareAddress2(di.getJID());
    			if(tmp_uid.equals(key))
    		    	return i;
    		    i++;
    		}
    	return -1;
    }
    
	private List<ContactGroup> friends_cGroup_select = new ArrayList<ContactGroup>();
	@Override
    public void onClick(View v) {
//    	RequestMap map;
        switch (v.getId()) {
            case R.id.makesureBtn:
            	CheckedImg img;
            	int idx = -1;
            	for(int i=0;i<checkedList.size();i++){
            		img = (CheckedImg)checkedList.get(i);
            		idx = containsKey(img.id);
            		if(idx!=-1)
            			friends_cGroup_select.add(friends_cGroup.get(idx));
            	}
            	setResult(RESULT_OK, new Intent().putExtra("newmembers", (Serializable)friends_cGroup_select));
				finish();
            	break;
        }
    }
	/**
	 * 根据name查询对应的索引.
	 * 
	 * @param name
	 * @return
	 */
	private int findCheckedPositionByName(String name) {
		int i = -1;
		for (CheckedImg m : checkedList) {
			i++;
			if (name.equals(m.name)) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ArrayList<HashMap<String, Object>> list = adapter.getData();
		Map<Integer, Boolean> checkedMap = adapter.getCheckedMap();
		HashMap<String, Object> map = list.get(position);
		LinearLayout layout = (LinearLayout)view;
//		RelativeLayout layout = (RelativeLayout) view;
//		LinearLayout layout2 = (LinearLayout) layout.getChildAt(1);
		RelativeLayout layout2 = (RelativeLayout)layout.getChildAt(0);
		LinearLayout layout3 = (LinearLayout)layout2.getChildAt(3);
		
		String _id = "" + map.get("id");
		String _name = "" + map.get("name");
		String _touxiang = "" + map.get("touxiang");

//		CheckBox ckb = (CheckBox) layout2.getChildAt(0);
		CheckBox ckb = (CheckBox) layout3.getChildAt(0);
		if (ckb.isChecked()) {
			checkedMap.put(Integer.parseInt(_id), false);
			removeByName(_name);
			checkedAdapter.notifyDataSetChanged();
		} else {
			checkedContack.setSelection(adapter.getCount()-1);
			checkedMap.put(Integer.parseInt(_id), true);
			addToCheckedList(_name, _id, _touxiang);
			checkedAdapter.notifyDataSetChanged();
			checkedContack.setSelection(checkedAdapter.getCount()-1);
		}
		adapter.notifyDataSetChanged();
	}
	
	
	private IRoster mRoster;
	 private HashMap cGroups = new HashMap();
	    private ArrayList cGroupsList = new ArrayList<ContactGroup>();
	    int AffiliationsCount = 0;
	    private String OwnerUid = "";
	    private String OwnerUsername = "";
	    private String CurrentUid = "";
	    private String CurrentUsername = "";
	    private String CurrentName = "";
	    private String CurrentAvatarpath = "";
		private String[] errorMsg = new String[]{"群成员信息获取成功.",
				"服务连接中1-1,请稍候再试.",
				"服务连接中1-2,请稍候再试.",
				"服务连接中1-3,请稍候再试.",
				"网络连接不可用,请检查你的网络设置.",
				"系统错误.群成员信息获取失败.",
				"群成员信息获取失败,hash校验失败"//0002
				};
		private int errorType = 5;
		String temp1 = "";
		String temp2 = "";
	    private boolean initGeGroupMembers(String tagid,String page,String keystr){//page=1 keystr=""
//	    	showCustomToast("initGeGroupMembers1");
	    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
			try{
				if(BeemConnectivity.isConnected(getApplicationContext())){
					Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
			    if(mXmppFacade!=null 
						&& mXmppFacade.getXmppConnectionAdapter()!=null 
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
						){
			    	    mRoster = mXmppFacade.getXmppConnectionAdapter().getRoster();
			    	    friends_cGroup = mRoster.getContactList();//List<ContactGroup> 包含了好友及已加入或创建的群组
			    	    Log.e("响应packet结果解析friends_cGroup...............", "friends_cGroup="+friends_cGroup.size()); 
//			    	    GroupNew2Activity.this.runOnUiThread(new Runnable() {
//			    				                    	
//			    		    							@Override
//			    		    							public void run() {
//			    		    								showCustomToast("服务器应答消息：friends_cGroup.size()="+friends_cGroup.size());
//			    		    							}
//			    		    						});
			    	    
			    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
			    	    ViewGroupMemberIQ reqXML = new ViewGroupMemberIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
			            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
			            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
			            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
			            Log.e("================20171218 GroupNew2Activity.java ================", "++++++++++++++20171218CurrentAvatarpath++++++++++++++"+CurrentAvatarpath);
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
			    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			    	    CurrentUsername = username;
//			            reqXML.setUsername(username);
			            reqXML.setTagid(tagid);
			            reqXML.setPage(page);
			            reqXML.setKeystr(keystr);
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
			            reqXML.setUuid(uuid);
		//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "viewgroupmemberiq"; 
			    		String namespace = "com:isharemessage:viewgroupmemberiq";
			    		ViewGroupMemberIQResponseProvider provider = new ViewGroupMemberIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "viewgroupmemberiq", "com:isharemessage:viewgroupmemberiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof ViewGroupMemberIQResponse) {
			                	final ViewGroupMemberIQResponse viewGroupMemberIQResponse = (ViewGroupMemberIQResponse) rt;
		
			                    if (viewGroupMemberIQResponse.getChildElementXML().contains(
			                            "com:isharemessage:viewgroupmemberiq")) {
		//	    					MainActivity.this.runOnUiThread(new Runnable() {
		//		                    	
		//    							@Override
		//    							public void run() {
		//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
		//    							}
		//    						});
			                        String Id = viewGroupMemberIQResponse.getId();
			                        String Apikey = viewGroupMemberIQResponse.getApikey();
			                        cGroups = viewGroupMemberIQResponse.getCGroups();
			                        AffiliationsCount = cGroups.size();
			                        if(cGroups.size()!=0){
				                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
//				                        return true;
				                        Iterator iter = cGroups.entrySet().iterator();
				            			Map.Entry entry = null;
				            			Object key = null;
				            			Object val = null;
				            			ContactGroup cGroup = null;
				            			while (iter.hasNext()) {
				                			entry = (Map.Entry) iter.next();
				                			key = entry.getKey();
				                			val = entry.getValue();
				                			cGroup = (ContactGroup)val;
				                			cGroupsList.add(cGroup);
//				                			exitingMembers.add(cGroup.getUsername());
				                			exitingMembers.add(cGroup.getUid());
				                			//isfriend=true;2@0/allen
				                			System.out.println("al_rec.size()="+cGroups.size()+"uid-isfriend="+key+";"+cGroup.getUid()+"@0/"+cGroup.getUsername());
				                			if(((String)key).indexOf("0")!=-1){
				                				OwnerUid = cGroup.getUid();
				                				OwnerUsername = cGroup.getUsername();
//				                				break;
				                			}
				            			}
			                        }
			                        //打印：
//			                        String temp1 = "";
			                        for(int m=0;m<friends_cGroup.size();m++){
			                        	temp1 += friends_cGroup.get(m).getUid()+"|"+friends_cGroup.get(m).getUsername()+",";
			                        }
//			                        String temp2 = "";
			                        for(int n=0;n<exitingMembers.size();n++){
			                        	temp2 += exitingMembers.get(n)+",";
			                        }
			                        Log.e("对比信息","信息1="+temp1+";信息2="+temp2);
//			    					GroupNew2Activity.this.runOnUiThread(new Runnable() {
//				                    	
//		    							@Override
//		    							public void run() {
//		    								showCustomToast("对比信息：信息1="+temp1+";信息2="+temp2);
//		    							}
//		    						});
			                        delItem_friends_cGroup(exitingMembers);//删除掉已经加入群组的好友不显示
			                        String retcode = viewGroupMemberIQResponse.getRetcode();
			                        String memo = viewGroupMemberIQResponse.getMemo();
			                        if(retcode.equalsIgnoreCase("0000")){
			                        	errorType = 0;
			                        	return true;
			                        }
			                        else if(retcode.equalsIgnoreCase("0002"))
			                        	errorType = 6;
			                        else
			                        	errorType = 5;
			                        
			                    }
			                } 
			            }
			    		errorType = 1;

			    }else
			    	errorType = 1;
			    
				}else
					errorType = 4;
			}catch(RemoteException e){
				e.printStackTrace();
				errorType = 2;
			}catch(Exception e){
				e.printStackTrace();
				errorType = 3;
			}
			return false;
	    }
	    
	    private boolean flag = false;
		private boolean isWork = false;
		private void getGroupMembers(final String tagid) {
//			showCustomToast("getGroupMembers1");
			Log.e("================GroupDetailsActivity.java ================", "++++++++++++++getGroupMembers111++++++++++++++");
			if(!isWork){
			putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					showLoadingDialog("正在加载,请稍后...");
				}

				@Override
				protected Boolean doInBackground(Void... params) {
					return initGeGroupMembers(tagid,"1","");
				}

				@Override
				protected void onPostExecute(Boolean result) {
					super.onPostExecute(result);
					dismissLoadingDialog();
					if (result) {	
//						mHandler.sendEmptyMessage(1);
						mHandler.sendEmptyMessage(MESSAGE_BIND_FRIEND_LIST);
					}else{
						//提示没有获取到数据：可能网络问题
//						mHandler.sendEmptyMessage(0);
					}
					flag = false;
					isWork = false;
				}

			});
			isWork = true;
			}
		}
	/**
    * The service connection used to connect to the Beem service.
    */
   private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
//		    	try{
//			    	CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
//		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
//		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
//		    	    CurrentUsername = username;
//		    	}catch(Exception e){
//		    		e.printStackTrace();
//		    	}
	    	    mBinded = true;//20130804 added by allen
		    }
		    if(groupId!=null
		    		&& !groupId.equalsIgnoreCase("null")
		    		&& groupId.length()!=0)
		    	getGroupMembers(groupId);
		    else
		    	getGroupMembers("1");//测试用
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    mXmppFacade = null;
		    mBinded = false;
		}
   }

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(GroupNew2Activity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(GroupNew2Activity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
//			getContactList(ConstantValues.refresh);
//			startActivity(new Intent(OtherProfileActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			Intent intent =  new Intent(GroupNew2Activity.this, ContactFrameActivity.class);
	    	intent.putExtra("refreshroster", "true");
			startActivity(intent);
			GroupNew2Activity.this.finish();
		}
	}
	
    public void onPause() {
    	super.onPause();
//    	mImageFetcher.setExitTasksEarly(true);
    	Log.e("================2015 TestActivity.java ================", "++++++++++++++onPause()++++++++++++++mBinded="+mBinded);
    }
	@Override
    protected void onResume() {
    	Log.e("================20170507 MainListActivity onResume================", "+++++++onResume+++++++");
		super.onResume();
//		mImageFetcher.setExitTasksEarly(false);
		isWork = false;
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mImageFetcher.onCancel();
        clearAsyncTask();
        if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
    }
}
